//获取部门信息和职位信息绑定到下拉框
// 获取到用户输入的信息，
//      格式校验
//      发送请求
let useraddModule = (function () {
    let $username = $('.username'),
        $spanusername = $('.spanusername'),
        $man = $('#man'),
        $woman = $('#woman'),
        $useremail = $('.useremail'),
        $spanuseremail = $('.spanuseremail'),
        $userphone = $('.userphone'),
        $spanuserphone = $('.spanuserphone'),
        $userdepartment = $('.userdepartment'),
        $userjob = $('.userjob'),
        $userdesc = $('.userdesc'),
        $submit = $('.submit');
    //绑定部门和植物的信息
    async function bindDepartAndJob() {
        // 首先看本地是否存在缓存信息，如果存在，在验证时效性，不存在或过期了，我们重新发送请求。
        let departmentData = null,
            jobData = null,
            isStorage = false;
        let departmentAndJob = localStorage.getItem('departmentAndJob');
        if (departmentAndJob) {
            departmentAndJob = JSON.parse(departmentAndJob);
            if (new Date().getTime() - departmentAndJob.time < 86400000) {
                [departmentData, jobData] = departmentAndJob.data;
                isStorage = true;
            }
        }

        if (!isStorage) {
            //ajax并行获取数据
            [departmentData, jobData] = await axios.all([
                axios.get('/department/list'),
                axios.get('/job/list')
            ]);
            // 获取信息后，先把信息缓存到本地（时效一天）
            localStorage.setItem('departmentAndJob', JSON.stringify({
                time: new Date().getTime(),
                data: [departmentData, jobData]
            }))
        }

        if (departmentData.code == 0) {
            departmentData = departmentData.data;
            let str = ``;
            departmentData.forEach(element => {
                str += `<option value="${element.id}">${element.name}</option>`
            });
            $userdepartment.html(str);
        }
        if (jobData.code == 0) {
            jobData = jobData.data;
            let str = ``;
            jobData.forEach(element => {
                str += `<option value="${element.id}">${element.name}</option>`
            });
            $userjob.html(str);
        }
    }

    // 表单校验
    // 表单校验
	// 1.用户名非空校验
	let checkUserName = function () {
		let text = $username.val().trim();
		if (text.length === 0) {
			$spanusername.html('用户名不能为空 !');
			return false;
		}
		$spanusername.html('');
		return true;
	};
	$username.on('blur', checkUserName);

	// 2.邮箱的校验
	let checkUserEmail = function () {
		let text = $useremail.val().trim();
		if (text.length === 0) {
			$spanuseremail.html('邮箱不能为空 !');
			return false;
		}
		let reg = /^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
		if (!reg.test(text)) {
			$spanuseremail.html('邮箱格式不正确 !');
			return false;
		}
		$spanuseremail.html('');
		return true;
	};


	// 3.手机号码校验
	let checkUserPhone = function () {
		let text = $userphone.val().trim();
		if (text.length === 0) {
			$spanuserphone.html('手机号码不能为空 !');
			return false;
		}
		let reg = /^1\d{10}$/;
		if (!reg.test(text)) {
			$spanuserphone.html('手机号码格式不正确 !');
			return false;
		}
		$spanuserphone.html('');
		return true;
	};


	// 4.用户描述信息的格式校验
	let checkUserDesc = function () {
		let text = $userdesc.val().trim(),
			$spanuserdesc = $('.spanuserdesc');
		if (text.length === 0) {
			$spanuserdesc.html('用户描述信息不能为空 !');
			return false;
		}
		$spanuserdesc.html('');
		return true;
	};

    
    // 点击提交按钮
    async function submitHandle(){
        if(!checkUserEmail()||!checkUserName()||!checkUserPhone) return;

        let params = {
            name:$username.val().trim(),
            sex:$man.prop('checked')?0:1,
            email:$useremail.val().trim(),
            phone:$userphone.val().trim(),
            departmentId:$userdepartment.val(),
            jobId:$userjob.val().trim(),
            desc:$userdesc.val().trim()
        }
        // 向服务器传请求
        let result = await axios.post('/user/add',params);
        if(result.code==0){
            alert('添加用户成功');
            window.location.href = '../page/userlist.html';
            return;
        }
        alert('网络繁忙');
    }
    return {
        init() {
            bindDepartAndJob();

            // 文本失去焦点的时候
            $username.blur(checkUserName);
            $useremail.blur(checkUserEmail);
            $userphone.blur(checkUserPhone);
            $userdesc.blur(checkUserDesc);

            $submit.click(submitHandle);
        }
    }
})();
useraddModule.init();